using System;
using System.Collections.Generic;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
using Terra.Core.Common.ApiResponse;
using Terra.Core.Common.Models.Pagination;
using Terra.Data.Models.Loggings;
using Terra.Service.Logging.DTOs;
using Terra.Service.Logging.Interfaces;
using Terra.WebApi.Filters;

namespace Terra.WebApi.Areas.Admin.Controllers;

/// <summary>
/// 系统日志控制器
/// </summary>
[Area("Admin")]
[Route("api/admin/logs")]
[ApiExplorerSettings(GroupName = "v1-admin")]
[Authorize]
[ApiController]
public class LogController : ControllerBase
{
    private readonly ILoginLogService _loginLogService;
    private readonly IExceptionLogService _exceptionLogService;

    /// <summary>
    /// 构造函数
    /// </summary>
    /// <param name="loginLogService">登录日志服务</param>
    /// <param name="exceptionLogService">异常日志服务</param>
    public LogController(
        ILoginLogService loginLogService,
        IExceptionLogService exceptionLogService)
    {
        _loginLogService = loginLogService;
        _exceptionLogService = exceptionLogService;
    }

    #region 登录日志

    /// <summary>
    /// 分页查询登录日志
    /// </summary>
    /// <param name="request">查询参数</param>
    /// <returns>分页结果</returns>
    [HttpGet("login")]
    [ProducesResponseType(typeof(ApiResponse<PagedList<LoginLogDto>>), 200)]
    public async Task<IActionResult> GetLoginLogsAsync([FromQuery] LoginLogPagedRequest request)
    {
        var response = await _loginLogService.GetPagedListAsync(request);
        return response.IsSuccess ? Ok(response) : BadRequest(response);
    }

    /// <summary>
    /// 获取最近一周登录日志
    /// </summary>
    /// <returns>最近一周的登录日志</returns>
    [HttpGet("login/recent")]
    [ProducesResponseType(typeof(ApiResponse<PagedList<LoginLogDto>>), 200)]
    public async Task<IActionResult> GetRecentLoginLogsAsync()
    {
        var request = new LoginLogPagedRequest
        {
            StartTime = DateTime.Now.AddDays(-7),
            EndTime = DateTime.Now,
            PageSize = 50,
            OrderBy = "LoginTime",
            IsDescending = true
        };

        var response = await _loginLogService.GetPagedListAsync(request);
        return response.IsSuccess ? Ok(response) : BadRequest(response);
    }

    /// <summary>
    /// 按用户名搜索登录日志
    /// </summary>
    /// <param name="userName">用户名</param>
    /// <returns>用户的登录日志</returns>
    [HttpGet("login/by-user/{userName}")]
    [ProducesResponseType(typeof(ApiResponse<PagedList<LoginLogDto>>), 200)]
    [ProducesResponseType(typeof(ApiResponse), 400)]
    public async Task<IActionResult> GetUserLoginLogsAsync(string userName)
    {
        if (string.IsNullOrWhiteSpace(userName))
        {
            return BadRequest(ApiResponse.Error("LOG001", "用户名不能为空"));
        }

        var request = new LoginLogPagedRequest
        {
            UserName = userName,
            PageSize = 20,
            OrderBy = "LoginTime",
            IsDescending = true
        };

        var response = await _loginLogService.GetPagedListAsync(request);
        return response.IsSuccess ? Ok(response) : BadRequest(response);
    }

    /// <summary>
    /// 清理指定时间之前的登录日志
    /// </summary>
    /// <param name="beforeTime">清理该时间之前的日志</param>
    /// <returns>清理的记录数</returns>
    [HttpDelete("login/clean")]
    [ProducesResponseType(typeof(ApiResponse<int>), 200)]
    [ProducesResponseType(typeof(ApiResponse), 400)]
    public async Task<IActionResult> CleanLoginLogsAsync([FromQuery] DateTime beforeTime)
    {
        if (beforeTime > DateTime.Now)
        {
            return BadRequest(ApiResponse.Error("LOG002", "清理时间不能大于当前时间"));
        }

        var response = await _loginLogService.CleanAsync(beforeTime);
        return response.IsSuccess ? Ok(response) : BadRequest(response);
    }

    /// <summary>
    /// 清理指定天数之前的登录日志
    /// </summary>
    /// <param name="days">保留天数</param>
    /// <returns>清理的记录数</returns>
    [HttpDelete("login/clean/{days:int}")]
    [ProducesResponseType(typeof(ApiResponse<int>), 200)]
    [ProducesResponseType(typeof(ApiResponse), 400)]
    public async Task<IActionResult> CleanLoginLogsByDaysAsync(int days)
    {
        if (days < 0)
        {
            return BadRequest(ApiResponse.Error("LOG003", "保留天数必须大于等于0"));
        }

        var beforeTime = DateTime.Now.AddDays(-days);
        var response = await _loginLogService.CleanAsync(beforeTime);
        return response.IsSuccess ? Ok(response) : BadRequest(response);
    }

    #endregion

    #region 操作日志
    // TODO: 添加操作日志相关接口
    #endregion

    #region 异常日志

    /// <summary>
    /// 分页查询异常日志
    /// </summary>
    /// <param name="query">查询参数</param>
    /// <returns>分页结果</returns>
    [HttpGet("exception")]
    [ProducesResponseType(typeof(ApiResponse<PagedList<ExceptionItemDto>>), 200)]
    public async Task<IActionResult> GetExceptionLogsAsync([FromQuery] ExceptionQueryDto query)
    {
        var response = await _exceptionLogService.GetPagedListAsync(query);
        return response.IsSuccess ? Ok(response) : BadRequest(response);
    }

    /// <summary>
    /// 获取最近的异常日志
    /// </summary>
    /// <param name="hours">最近小时数，默认24小时</param>
    /// <returns>最近的异常日志</returns>
    [HttpGet("exception/recent")]
    [ProducesResponseType(typeof(ApiResponse<PagedList<ExceptionItemDto>>), 200)]
    public async Task<IActionResult> GetRecentExceptionLogsAsync([FromQuery] int hours = 24)
    {
        var query = new ExceptionQueryDto
        {
            StartTime = DateTime.Now.AddHours(-hours),
            EndTime = DateTime.Now,
            PageSize = 50,
            OrderBy = "ExceptionTime",
            IsDescending = true
        };

        var response = await _exceptionLogService.GetPagedListAsync(query);
        return response.IsSuccess ? Ok(response) : BadRequest(response);
    }

    /// <summary>
    /// 获取异常日志详情
    /// </summary>
    /// <param name="id">异常日志ID</param>
    /// <returns>异常日志详情</returns>
    [HttpGet("exception/{id:guid}")]
    [ProducesResponseType(typeof(ApiResponse<ExceptionDetailDto>), 200)]
    [ProducesResponseType(typeof(ApiResponse), 404)]
    public async Task<IActionResult> GetExceptionLogByIdAsync(Guid id)
    {
        var response = await _exceptionLogService.GetByIdAsync(id);
        if (!response.IsSuccess)
        {
            return NotFound(response);
        }
        return Ok(response);
    }

    /// <summary>
    /// 获取异常统计信息
    /// </summary>
    /// <param name="startTime">开始时间</param>
    /// <param name="endTime">结束时间</param>
    /// <returns>异常统计信息</returns>
    [HttpGet("exception/stats")]
    [ProducesResponseType(typeof(ApiResponse<List<ExceptionStatsDto>>), StatusCodes.Status200OK)]
    public async Task<IActionResult> GetExceptionStatsAsync(DateTime? startTime, DateTime? endTime)
    {
        var result = await _exceptionLogService.GetExceptionStatsAsync(startTime, endTime);
        return Ok(result);
    }

    /// <summary>
    /// 获取异常统计数据（前端格式）
    /// </summary>
    /// <param name="startTime">开始时间，默认过去7天</param>
    /// <param name="endTime">结束时间，默认当前时间</param>
    /// <returns>异常统计数据（前端格式）</returns>
    [HttpGet("exception/frontend-stats")]
    [ProducesResponseType(typeof(ApiResponse<List<ExceptionStatsFrontendDto>>), StatusCodes.Status200OK)]
    public async Task<IActionResult> GetFrontendStatsAsync(DateTime? startTime, DateTime? endTime)
    {
        var result = await _exceptionLogService.GetFrontendStatsAsync(startTime, endTime);
        return Ok(result);
    }

    /// <summary>
    /// 清理指定天数之前的异常日志
    /// </summary>
    /// <param name="days">保留天数</param>
    /// <returns>清理的记录数</returns>
    [HttpDelete("exception/clean/{days:int}")]
    [ProducesResponseType(typeof(ApiResponse<int>), 200)]
    [ProducesResponseType(typeof(ApiResponse), 400)]
    public async Task<IActionResult> CleanExceptionLogsByDaysAsync(int days)
    {
        if (days < 0)
        {
            return BadRequest(ApiResponse.Error("LOG005", "保留天数必须大于等于0"));
        }

        var beforeTime = DateTime.Now.AddDays(-days);
        var response = await _exceptionLogService.CleanAsync(beforeTime);
        return response.IsSuccess ? Ok(response) : BadRequest(response);
    }

    /// <summary>
    /// 批量删除异常日志
    /// </summary>
    /// <param name="ids">日志ID列表</param>
    /// <returns>删除的记录数</returns>
    [HttpDelete("exception/batch")]
    [ProducesResponseType(typeof(ApiResponse<int>), 200)]
    [ProducesResponseType(typeof(ApiResponse), 400)]
    public async Task<IActionResult> BatchDeleteExceptionLogsAsync([FromBody] List<Guid> ids)
    {
        if (ids == null || !ids.Any())
        {
            return BadRequest(ApiResponse.Error("LOG006", "请选择要删除的日志"));
        }

        var response = await _exceptionLogService.BatchDeleteAsync(ids);
        return response.IsSuccess ? Ok(response) : BadRequest(response);
    }

    /// <summary>
    /// 导出异常日志
    /// </summary>
    /// <param name="query">查询参数</param>
    /// <returns>CSV文件</returns>
    [HttpGet("exception/export")]
    [ProducesResponseType(typeof(FileContentResult), 200)]
    [ProducesResponseType(typeof(ApiResponse), 400)]
    public async Task<IActionResult> ExportExceptionLogsAsync([FromQuery] ExceptionQueryDto query)
    {
        var response = await _exceptionLogService.ExportAsync(query);
        if (!response.IsSuccess)
        {
            return BadRequest(response);
        }

        return File(
            response.Data,
            "text/csv",
            $"exception_logs_{DateTime.Now:yyyyMMddHHmmss}.csv"
        );
    }

    #endregion

    #region 请求日志
    // TODO: 添加请求日志相关接口
    #endregion
}